package com.jnu.testdrivendevelopment;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentActivity;
import androidx.viewpager2.adapter.FragmentStateAdapter;
import androidx.viewpager2.widget.ViewPager2;

import android.os.Bundle;

import com.google.android.material.tabs.TabLayout;
import com.google.android.material.tabs.TabLayoutMediator;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {

    private String[] tabTitles=new String[3];
    private List<Fragment> mDatas=new ArrayList<>();
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        tabTitles= new String[]{"图书","新闻","卖家"};
        mDatas.add(BookFragment.newInstance());
        mDatas.add(WebViewFragment.newInstance("test1","test2"));
        mDatas.add(MapViewFragment.newInstance("test1","test2"));
        //mDatas.add(GameFragment.newInstance("test1","test2"));

        ViewPager2 viewPagerFragments=findViewById(R.id.viewPager2_content);
        viewPagerFragments.setAdapter(new MyFragmentAdpater(this));

        TabLayout tabLayoutHeader=findViewById(R.id.tabLayout_header);
        TabLayoutMediator tabLayoutMediator=new TabLayoutMediator(tabLayoutHeader, viewPagerFragments, new TabLayoutMediator.TabConfigurationStrategy() {
            @Override
            public void onConfigureTab(@NonNull TabLayout.Tab tab, int position) {
                tab.setText(tabTitles[position]);
            }
        });
        tabLayoutMediator.attach();
    }
    private class MyFragmentAdpater extends FragmentStateAdapter{

        public MyFragmentAdpater(@NonNull FragmentActivity fragmentActivity) {
            super(fragmentActivity);
        }

        @NonNull
        @Override
        public Fragment createFragment(int position) {
            return mDatas.get(position);
        }

        @Override
        public int getItemCount() {
            return 3;
        }
    }
}